
import { createStore } from 'vuex'
import {State} from '../types/vuex'

//购物车数据全部从本地读取
//存
function setCartList(state:State){
  const {cartList} = state
  localStorage.setItem("cartList",JSON.stringify(cartList))
}
//取
function getCartList(){
  const cartList = localStorage.getItem("cartList")
  if(cartList){
    return JSON.parse(cartList)
  }else{
    return {}
  }
}
// 创建一个新的 store 实例
const store = createStore<State>({
  state () {
    return {
      cartList:getCartList()
    }
  },
  mutations: {
    changeCart(state,payload){
        // console.log(payload);
        const {item,shopId,num,shopName} = payload
        // console.log("shopName",shopName);
        
        // let a:string = "a"
        let shopInfo = state.cartList[shopId]
        if(!shopInfo){
            shopInfo={}
            console.log("shopName",shopName);
            shopInfo.shopName = shopName
            shopInfo.productList = {}
        }
        
        let productId = item.id
        let product =shopInfo.productList[productId]    
        if(!product){
          product = item
          product.count = 0;
        }
        product.count+=num;
        // console.log(product.count);
        if(product.count>0){
          product.isCheck = true
        }
        if(product.count <= 0){
          product.count = 0
        }
        shopInfo.productList[productId] = product
        state.cartList[shopId] = shopInfo
        console.log(state);
        
        setCartList(state)
    },
    changeCheck(state,payload){
        const {item,id} = payload
        console.log(item);
        item.isCheck = !item.isCheck
    },
    changeCheckAll(state,payload){
      const {checkAll,shopId} = payload
      console.log("checkAll",checkAll);
      
      let shopInfo = state.cartList[shopId]
      console.log("shopInfo",shopInfo);
      
      if(shopInfo){ 
        for(const key in shopInfo.productList){
          const p = shopInfo.productList[key]
          p.isCheck = !checkAll
        }
      }
    },
    //清空购物车
    clearCartList(state,payload){
      const {shopId } = payload
      state.cartList[shopId] = {}
      setCartList(state)
    }

  },
  actions:{

  }
})
export default store